import {
	$loading,
	$msg
} from "./msg"
import Axios from "axios"
import { API as $API, BASE_URL as baseURL } from './api'
import $CACHE from './cache'

const http = function (config) {
    config = JSON.parse(JSON.stringify(config));
    let {
        cache = false,
        header = {},
        method,
    } = config;
    if ({}.toString.call(config.url).slice(8, -1) == "Array") {
        let urls = config.url;
        let urlType = urls.shift();
        config.url = (config.baseURL || baseURL) + ($API[urlType] || `/${urlType.replace(/^\/*/, '')}/`) + urls.join('/');
    } else {
        config.url = (config.baseURL || baseURL) + ($API[config.url] || `/${config.url.replace(/^\/*/, '')}`);
    }
    const accessToken = ""
    config.header = {
        ["Content-Type"]: method === 'GET' ? "application/x-www-form-urlencoded;charset=UTF-8" : "application/json",
        ['X-Access-Token']: accessToken,
        ['Authorization']: "Basic c2FiZXI6c2FiZXJfc2VjcmV0",
        ...config.header
    };
    return new Promise((resolve, reject) => {
        if (cache == true && $CACHE[config.url]) {
            resolve($CACHE[config.url]);
            return;
        } else if ($CACHE[config.url]) {
            delete $CACHE[config.url];
        }
        config.isLoading !== false && $loading.show();
        Axios.request({
            ...config,
        }).then((res) => {
            config.isLoading !== false && $loading.hide();
            if (config.isFilter === false) {
                resolve(res);
                return
            }
            let {
                code,
                message="服务器异常!",
                data,
                result = data,
            } = res.data;
            if (config.isFilter === false) {
                resolve(res.data);
            } else if ([200].indexOf(code) != -1) {
                if (cache == true) $CACHE[config.url] = result;
                resolve(result);
            } else {
                config.isError !== false && $msg.warning(message);
                reject(res.data);
            }
        }).catch((err) => {
            config.isLoading !== false && $loading.hide();
            config.isError !== false && $msg.error("请求失败");
            reject(err);
        })
    })
};

http.get = function (url, params, config = {}) {
    config.method = "GET";
    config.url = config.url || url;
    config.params = params;
    return http(config);
};
http.post = function (url, data, params, config = {}) {
    config.method = "POST";
    config.url = config.url || url;
    config.data = data;
    config.params = params;
    return http(config);
};

function install(app) {
    app.config.globalProperties['$http'] = http;
    app.config.globalProperties['$msg'] = $msg;
    app.config.globalProperties['$loading'] = $loading;
}

export * from "./msg"
export * from './api'
export {
    install,
    http as $http,
	$CACHE as $cache,
	$loading
}